package com.hnguigu.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection prin) {
        //获取当前登录人账号
        Object username = prin.getPrimaryPrincipal();

        Set roles = new HashSet<String>();


        if(username.equals("tome")){
            roles.add("test1");
        }
            roles.add("test2");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取当前账号
        String principal =(String) token.getPrincipal();
        //计算盐值
        ByteSource bytes = ByteSource.Util.bytes(principal);
        //获取当前密码
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(principal,"c34af346c89b8b03438e27a32863c9b5",bytes,getName());

        return simpleAuthenticationInfo;
    }

    public static void main(String[] args) {
        SimpleHash hash=new SimpleHash("MD5","1234","tome",1024);
        SimpleHash hash1=new SimpleHash("MD5","1234","admin",1024);
        System.out.println(hash);
        System.out.println(hash1);
    }
}
